package com.apimarket.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @Description:
 * @Author ZXR
 * @Date 2021/7/9 13:44
 * @Version 1.0
 */

@Data
@Configuration
@MapperScan(basePackages = MaterDataBaseConfig.PACKAGE ,sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MaterDataBaseConfig {
    /**
     * Dao层包路径
     * 这里加private会爆红
     */
    static final String PACKAGE="com.apimarket.dao";

    /**
     * mapper文件的相对路径
     */
    private static final String MAPPER_LOCATION="classpath*:mapper/master/*.xml";


    //创建主数据源
    //主数据源用@Primary注解进行标识
    @Primary //配置默认数据源
    @Bean(name="masterDataSource")
    //前缀为primary.datasource.druid的配置信息
    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    public DataSource primaryDataSource(){
        return new DruidDataSource();
    }

    //创建主数据源的事务管理
    @Primary
    @Bean(name="masterTransactionManager")
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource")DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    //创建Mybatis的连接会话工厂实例
    @Primary
    @Bean(name = "masterSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);  // 设置数据源bean
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MaterDataBaseConfig.MAPPER_LOCATION));  // 设置mapper文件路径

        return sessionFactory.getObject();
    }
}
